//
//  CouponCheckViewController.m
//  HAODE
//
//  Created by panquanReabam.com on 16/5/23.
//  Copyright © 2016年 reabam.com. All rights reserved.
//

#import "CouponCheckViewController.h"
#import "UIViewExt.h"
#import "HttpRequest.h"
#import "RDVTabBarController.h"
#import "MJRefresh.h"
#import "UIButton+WebCache.h"
#import "TheLoginViewController.h"
#import "UMSocial.h"
#import "CouponListModel.h"
#import "CouponCheckCell.h"
@interface CouponCheckViewController ()<MBProgressHUDDelegate,UIGestureRecognizerDelegate,UINavigationControllerDelegate,UITextFieldDelegate,UISearchBarDelegate>

@end

@implementation CouponCheckViewController

{
    UIView*submitView;
    UIView*submitV;
    UILabel*prompt;
    UILabel*totalPriceLabel;
    UILabel*InventoryLabel;
    UIImageView*seximage;
    UITableView *table;
    UIView*heardView;
    UIButton*submit;
}
@synthesize alt = alt;
@synthesize mDelegate;
-(void)BackAction:(UIButton *)sender{
    [mDelegate secondViewController:self titleCouponArray:self.titleArray priceCouponArray:self.priceArray  beginDateCouponArray:self.beginDateArray qtyCouponArray:self.qtyArray imageUrlCouponArray:self.imageUrlFullArray :self.endDateArray useLimitAmtCouponArray:self.titleArray couponIdArray:self.couponIdArray :self.snArray];
    [self.navigationController popViewControllerAnimated:YES];

}
- (void)viewDidDisappear:(BOOL)animated{
    
    [super viewDidDisappear:animated];
    self.navigationController.delegate = nil;
    
}
- (void)viewDidLoad
{
    
    [super viewDidLoad];
    self.BeUsed=@"";
    table = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight) style:UITableViewStylePlain];
    table.delegate = self;
    table.dataSource = self;
    table.separatorStyle=UITableViewCellSeparatorStyleNone;
    [table registerClass:[CouponCheckCell class] forCellReuseIdentifier:@"CouponCheckViewController"];
    [self.view addSubview:table];
    totalPriceLabel=[[UILabel alloc]initWithFrame:CGRectMake(0, ScreenHeight-48, ScreenWidth*430/750, 48)];
    totalPriceLabel.backgroundColor=backColor;
    totalPriceLabel.textColor= [UIColor whiteColor] ;
    totalPriceLabel.alpha=0.8;
    [self.view addSubview:totalPriceLabel];
    submit=[[UIButton alloc]initWithFrame:CGRectMake(ScreenWidth*430/750, ScreenHeight-48, ScreenWidth*320/750, 48)];
    [submit setTitle:@"确定核销" forState:UIControlStateNormal];
    submit.backgroundColor=luseColor;
    [submit setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [submit addTarget:self action:@selector(submit:) forControlEvents:UIControlEventTouchUpInside];
    [submit setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.view addSubview:submit];
    [self requestData];
}

-(void)requestData{
    [table reloadData];
    if (self.titleArray.count==0) {
        prompt=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
        prompt.text= @"请搜索或者扫描商品开始服务！";
        prompt.textAlignment=NSTextAlignmentCenter;
        prompt.backgroundColor=[UIColor whiteColor];
        prompt.font= [UIFont systemFontOfSize:contenfot];
        [prompt setTextColor:[UIColor blackColor]];
        [self.view addSubview:prompt];
    }else {
        [prompt  removeFromSuperview];
        NSNumber *sum11 = [self.priceArray valueForKeyPath:@"@sum.floatValue"];
        NSString*GoldPrice=[NSString stringWithFormat:@"%@",sum11];
        NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
        [numberFormatter setPositiveFormat:@"###,##0.00;"];
        NSString *formattedNumberString = [numberFormatter stringFromNumber:[NSNumber numberWithDouble:GoldPrice.floatValue]];
        [self priceStr:formattedNumberString];
    }
    heardView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth,80/2)];
    heardView.backgroundColor=zuiqianhuiColor;
    table .tableHeaderView=heardView;
    InventoryLabel=[[UILabel alloc]init];
    InventoryLabel.text=[NSString stringWithFormat:@"%@(%@)",self.userName,self.phone];
    InventoryLabel.textColor=[UIColor blackColor];
    InventoryLabel.font=[UIFont systemFontOfSize:16];
    [heardView addSubview:InventoryLabel];
    seximage=[[UIImageView alloc]init];
    if ([self.sex isEqualToString:@"男"]) {
            seximage.image=[UIImage imageNamed:@"nan"];
        }else{
           seximage.image=[UIImage imageNamed:@"nv"];
        }
     [heardView addSubview:seximage];
    [self setViewAutoLayout];
 }



-(void)submit:(UIButton*)sender{
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString* Token = [user objectForKey:@"tokenId"];
    NSMutableDictionary *params = [NSMutableDictionary new];
    [params setValue:Token forKey:@"tokenId"];
   [params setValue:self.snArray  forKey:@"snList"];
    [HttpRequest requestData:@"Product/Detail" params:params success:^(BOOL isSuccess, SeverData *severDataDict) {
        NSLog(@"====%@",severDataDict.dataDict);
        if (isSuccess) {
            if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                self.BeUsed=@"BeUsed";
                totalPriceLabel.backgroundColor=[UIColor colorWithRed:228/255.0 green:228/255.0 blue:228/255.0 alpha:1.0];
                submit.backgroundColor=[UIColor colorWithRed:204/255.0 green:204/255.0 blue:204/255.0 alpha:1.0];
                submit.userInteractionEnabled=NO;
                [submit setTitle:@"已核销" forState:UIControlStateNormal];
                [self removeData];
                [self requestData];
            }else
            {
                NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                [Global showTextHudSub:requestResultStr view:self.view];
               }
        }
        else
        {
            [Global showTextHudSub:severDataDict.resultStr view:self.view];
        }
    }];

    
    

}
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.priceArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CouponCheckCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CouponCheckViewController"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.price.text=[NSString stringWithFormat:@"%@",  self.priceArray[indexPath.row]];
    cell.title.text=[NSString stringWithFormat:@"%@",  self.titleArray[indexPath.row]];
    cell.qty.text=[NSString stringWithFormat:@"发放数量 %@",self.qtyArray[indexPath.row]];
    cell.useLimitAmt.text=[NSString stringWithFormat:@"用券的最低金额 ¥ %@",self.useLimitAmtArray[indexPath.row]];
    NSRange range={0,10};
    NSString* string =[[NSString stringWithFormat:@"%@",[NSString stringWithFormat:@"%@",self.endDateArray[indexPath.row]]] substringWithRange:range];
    NSRange range1={0,10};
    NSString* string1 =[[NSString stringWithFormat:@"%@",[NSString stringWithFormat:@"%@",self.beginDateArray[indexPath.row]]] substringWithRange:range1];
    cell.beginDate.text=[NSString stringWithFormat:@"有效期 %@~%@",string,string1];
    if ([self.BeUsed isEqualToString:@"BeUsed"]) {
        cell.colorPieceView.backgroundColor=[UIColor colorWithRed:214/255.0 green:214/255.0 blue:214/255.0 alpha:1.0];
        cell.colorPieceView1.backgroundColor=[UIColor colorWithRed:204/255.0 green:204/255.0 blue:204/255.0 alpha:1.0];
        UIImageView*imageView=[[UIImageView alloc]initWithFrame:CGRectMake(ScreenWidth-70, 10, 60, 60)];
        imageView.image=[UIImage imageNamed: @"fenxiang-youhuiquan"];
        [cell.contentView addSubview:imageView];
    }
    return cell;
}

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return  130;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}
-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    return  UITableViewCellEditingStyleDelete;
    
}
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.beginDateArray removeObjectAtIndex:indexPath.row];//从指定索引移除
    [self.endDateArray removeObjectAtIndex:indexPath.row];//从指定索引移除
    [self.useLimitAmtArray removeObjectAtIndex:indexPath.row];//从指定索引移除
    [self.qtyArray removeObjectAtIndex:indexPath.row];//从指定索引移除
    [self.titleArray removeObjectAtIndex:indexPath.row];//从指定索引移除
    [self.priceArray  removeObjectAtIndex:indexPath.row];//从指定索引移除
    [self.couponIdArray removeObjectAtIndex:indexPath.row];//从指定索引移除
    [self.imageUrlFullArray removeObjectAtIndex:indexPath.row];//从指定索引移除
    [self.snArray removeObjectAtIndex:indexPath.row];//从指定索引移除
    [table deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    [self requestData];
    
}

- (void)showAlertWait
{
    alt = [[UIAlertView alloc] initWithTitle:@"网络不稳定 ！" message:@"请确认网络" delegate:self cancelButtonTitle:nil otherButtonTitles: nil];
    [alt show];
    
    [self performSelector:@selector(hideAlert) withObject:nil afterDelay:1.0f];
    
}

- (void)showAlertMessage:(NSString *)msg
{
    alt = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:msg delegate:nil cancelButtonTitle:nil otherButtonTitles: nil];
    [alt show];
    
    [self performSelector:@selector(hideAlert) withObject:nil afterDelay:1.0f];
}
- (void)hideAlert
{
    if (alt != nil)
    {
        [alt dismissWithClickedButtonIndex:0 animated:YES];
        alt = nil;
    }
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[self rdv_tabBarController] setTabBarHidden:YES];
    self.navigationController.navigationBar.barStyle = UIBaselineAdjustmentNone;
    UILabel *lineLabel=[[UILabel alloc] initWithFrame:CGRectMake(0, 43,ScreenWidth, 1)];
    [lineLabel setBackgroundColor:[UIColor colorWithRed:238.0/255.0 green:238.0/255.0 blue:238.0/255.0 alpha:1.0]];
    [self.navigationController.navigationBar addSubview:lineLabel];
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
    [[UINavigationBar appearance] setBarTintColor:Color];
    UIImage* backImage = [UIImage imageNamed:@"fanhui"];
    CGRect backframe = CGRectMake(0,0,30,30);
    UIButton* backButton= [[UIButton alloc] initWithFrame:backframe];
    [backButton setBackgroundImage:backImage forState:UIControlStateNormal];
    backButton.titleLabel.textAlignment=NSTextAlignmentLeft;
    [backButton addTarget:self action:@selector(BackAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    self.navigationController.delegate = self;
    
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
    
    self.title=@"扫描记录";
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                                                     [UIColor blackColor],
                                                                     UITextAttributeTextColor,
                                                                     [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:1],
                                                                     UITextAttributeTextShadowColor,
                                                                     [NSValue valueWithUIOffset:UIOffsetMake(0, 0)],
                                                                     UITextAttributeTextShadowOffset,
                                                                     [UIFont fontWithName:@"Helvetica Neue" size:tetlefot],
                                                                     UITextAttributeFont,nil]];
    
    self.navigationController.navigationBarHidden = NO;
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@""] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.shadowImage =[[UIImage alloc] init];
    
    
    
}
-(void)priceStr:(NSString *)str {
    totalPriceLabel .text= [NSString stringWithFormat:@"  合计 ￥%@",str] ;
    totalPriceLabel.font=[UIFont systemFontOfSize:18];
    NSMutableAttributedString *AttributedStr1 = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"  合计 ￥%@",str]];
    
    [AttributedStr1 addAttribute:NSFontAttributeName
     
                           value:[UIFont systemFontOfSize:14.0]
     
                           range:NSMakeRange(0, 6)];
    
    [AttributedStr1 addAttribute:NSForegroundColorAttributeName
     
                           value:[UIColor whiteColor]
     
                           range:NSMakeRange(0, 6)];
    totalPriceLabel.attributedText = AttributedStr1;
    
}
-(void)setViewAutoLayout
{
    [InventoryLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).with.offset(15) ;
        make.height.equalTo(@16);
        make.top.equalTo(heardView.mas_top).with.offset(25/2);
    }];
    
    [seximage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(InventoryLabel.mas_right).with.offset(5);
        make.width.equalTo(@20);
        make.height.equalTo(@20);
        make.top.equalTo(heardView.mas_top).with.offset(23/2);
    }];
    

    
    
}
-(void)removeData{
    [self.beginDateArray removeAllObjects];//从指定索引移除
    [self.endDateArray removeAllObjects];//从指定索引移除
    [self.useLimitAmtArray removeAllObjects];//从指定索引移除
    [self.qtyArray removeAllObjects];//从指定索引移除
    [self.titleArray removeAllObjects];//从指定索引移除
    [self.priceArray  removeAllObjects];//从指定索引移除
    [self.couponIdArray removeAllObjects];//从指定索引移除
    [self.imageUrlFullArray removeAllObjects];//从指定索引移除
    [self.snArray removeAllObjects];//从指定索引移除

}
@end
